package pl.wroc.uni.ii.puzzle.game;

import java.util.ArrayList;
import java.util.Random;

import pl.wroc.uni.ii.puzzle.view.GameView;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;

public class PlayBoard extends Board {

	private int rows;
	private int columns;
	private int cellWidth;
	private int cellHeight;
	private SelectionManager selectionManager;
	
	private ArrayList<Cell> cells;

	public PlayBoard(GameView gameView, int level, int screenWidth, int screenHeight, String hardship) {
		super(gameView, level);
		setHardship(hardship);
		cellWidth = screenWidth / columns;
		cellHeight = screenHeight / rows;
		createAndInitCells();
		selectionManager = new SelectionManager(this);
	}
	
	private void setHardship(String hardship) {
		if ("Easy".equals(hardship)) {
			rows = 5;
			columns = 5;		
		}
		else if ("Medium".equals(hardship)) {
			rows = 10;
			columns = 5;		
		}
		else  { //"Hard"
			rows = 15;
			columns = 10;		
		}
	}

	private void createAndInitCells() {
		cells = new ArrayList<Cell>(rows*columns);
		for (int i=0; i<rows; i++) {
			for (int j=0; j<columns; j++) {
				Cell cell = new Cell(i,j,cellWidth,cellHeight,bitmap);
				cells.add(cell);
			}
		}
		mixCells();
	}

	@Override
	public void draw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		drawCells(canvas);
	}
	
	private void drawCells(Canvas canvas) {
		for (Cell cell : cells) {
			cell.draw(canvas);
		}
	}

	private Cell getCellFromCoordinates(int x, int y) {
		int row = y / cellHeight;
		int column = x / cellWidth;
		
		if (row>=rows || column>=columns) {
			return null;
		}
		int position = row * columns + column;
		return cells.get(position);
	}

	@Override
	public void select(int x, int y) {
		Cell c = getCellFromCoordinates(x, y);
		if (c!= null) {
			selectionManager.select(c);			
		}
	}
	
	public void swapCellsPositionsAndRefreshState(Cell c1, Cell c2) {
		swapCellsPositions(c1, c2);

		if (isLevelCompleted()) {
			gameView.startNewLevel();
		}
	}
	
	private void swapCellsPositions(Cell c1, Cell c2) {
		Rect position = c1.getPosition();
		c1.setPosition(c2.getPosition());
		c2.setPosition(position);
	}
	
	private void mixCells() {
		int cellCount = rows*columns;
		Random random = new Random();
		Cell c1;
		Cell c2;
		for (int i=0; i<100; i++) {
			c1 = cells.get(random.nextInt(cellCount));
			c2 = cells.get(random.nextInt(cellCount));
			swapCellsPositions(c1, c2);
		}
		
		c1 = cells.get(1);
		c2 = cells.get(3);
		swapCellsPositions(c1, c2);
	}
	
	private boolean isLevelCompleted() {
		for (Cell c : cells) {
			if (!c.hasProperPosition()) {
				return false;
			}
		}
		return true;
	}
}
